package com.ljyh.cygnus.screens.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ljyh.cygnus.model.CommandUiState
import com.ljyh.cygnus.utils.RootCommandExecutor
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch

abstract class BaseViewModel : ViewModel() {

    protected fun executeRootCommands(
        stateFlow: MutableStateFlow<CommandUiState>,
        vararg commands: String
    ) {
        viewModelScope.launch {
            stateFlow.value = CommandUiState.Loading
            try {
                val output =    RootCommandExecutor.execute(*commands)
                if (output.isSuccess) {
                    stateFlow.value = CommandUiState.Success(output)
                } else {
                    val errorMessage = output.stderr.joinToString("\n")
                    stateFlow.value = CommandUiState.Error(errorMessage, output)
                }
            } catch (e: Exception) {
                e.printStackTrace()
                stateFlow.value =
                    CommandUiState.Error(e.message ?: "An unexpected error occurred", null)
            }
        }
    }

    protected fun resetState(stateFlow: MutableStateFlow<CommandUiState>) {
        stateFlow.value = CommandUiState.Idle
    }
}